package net.aramzamzam.tapestry.judo.components;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ClientElement;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.RenderSupport;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.SupportsInformalParameters;
import org.apache.tapestry5.dom.Element;
import org.apache.tapestry5.ioc.annotations.Inject;

/**
 * Renders an arbitrary element including informal parameters.
 */
@SupportsInformalParameters
public class Any implements ClientElement
{
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
    private String element;

    /**
     * The desired client id, which defaults to the components id.
     */
    @Parameter(value = "prop:componentResources.id", defaultPrefix = BindingConstants.LITERAL)
    private String clientId;

    private Element anyElement;

    private String uniqueId;

    @Inject
    private ComponentResources resources;

    @Inject
    private RenderSupport renderSupport;

    String defaultElement()
    {
        return resources.getElementName("div");
    }

    void beginRender(MarkupWriter writer)
    {
        anyElement = writer.element(element);

        uniqueId = null;

        resources.renderInformalParameters(writer);
    }

    /**
     * Returns the client id.  This has side effects: this first time this is called (after the Any component renders
     * its start tag), a unique id is allocated (based on, and typically the same as, the clientId parameter, which
     * defaults to the component's id). The rendered element is updated, with its id attribute set to the unique client
     * id, which is then returned.
     *
     * @return unique client id for this component
     */
    public String getClientId()
    {
        if (uniqueId == null)
        {
            uniqueId = renderSupport.allocateClientId(clientId);
        }

        return uniqueId;
    }

    void afterRender(MarkupWriter writer)
    {
        if (uniqueId!=null)
        	anyElement.forceAttributes("id", uniqueId);
    	writer.end(); // the element
    }

}
